#include "../include/Board.h"
#include <iostream>

Board::Board()
{
    m_board = std::vector<char>(9, ' ');
}

Board::~Board(){}

void Board::init()
{
    printBoard();
}

void Board::printBoard()
{
    cleanBoard();
    
    for(int i = 0; i < ROW; i++)
    {
        char line[] = " -------------";
        for(int j = 0; j < COL; j++)
        {
            std::cout << " | " << m_board[i * 3 + j];
        }
        std::cout << " |" << std::endl;
        if(i == mPoint.x)
        {
            line[(mPoint.y + 1) * 4 - 1] = '^';
        }
        std::cout << line << std::endl;
    }
}

bool Board::updateBoard(const XCY::NetPacket & pack)
{
    if(m_board[pack.point.x * 3 + pack.point.y] != ' ') 
        return false;

    m_visited.push(pack.point.x * 3 + pack.point.y);
    m_board[pack.point.x * 3 + pack.point.y] = XCY::CHEER[pack.nCurrent_player];
    printBoard();
    return true;
}

void Board::cleanBoard()
{
    system("clear");
}

bool Board::isFinish(char v)
{
    //行
    for(int i = 0; i < 3; i++)
    {
        if(m_board[i * 3] == v && m_board[i * 3 + 1] == v && m_board[i * 3 + 2] == v) 
            return true;
    }
    //列
    for(int i = 0; i < 3; i++)
    {
        if(m_board[0 * 3 + i] == v && m_board[1 * 3 + i] == v && m_board[2 * 3 + i] == v) 
            return true;
    }
    // 检查对角线
    if (m_board[0] == v && m_board[4] == v && m_board[8] == v) {
        return true;
    }
    if (m_board[2] == v && m_board[4] == v && m_board[6] == v) {
        return true;
    }
    return false;
}

void Board::deleteone()
{
    if(m_visited.size() == MAXCHEER)
    {
        m_board[m_visited.front()] = ' ';
        m_visited.pop();
        printBoard();
    }
}

void Board::setPoint(const XCY::CheerPoint &point)
{
    mPoint = point;
    printBoard();
}